package com.chalk.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xiaoqiang
 * @Description File 工具类
 * @date 2018/10/31 10:59
 */
public class FileUtil {

    /**
     * 读取到字节数组
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(File file) throws IOException {
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
            }
            return byteBuffer.array();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                channel.close();
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

